<template>
  <div class="box">
    <div class="search-box">
      <img src="../assets/img/back.png" class="back" @click="backPage"/>
      <div class="search-con">
        <img src="../assets/img/search.png" class="logo"/>
        <input type="text" class="search" placeholder="请输入城市名" v-model="keyword"/>
        <img src="../assets/img/icon_3.png" class="clear" v-show="showIcon">
      </div>
    </div>
    <div class="recently-box">
      <div class="title">最近访问</div>
      <div class="recently-con">
        <span class="hot" @click="selectCity('china')">全国</span>
        <span class="hot" v-for="(city,index) in cityList" :key="index" @click="selectCity(city)">{{city}}</span>
      </div>
    </div>
    <div class="list-view" ref="listView" v-if="showIndex">
      <ul>
        <li v-for="group in cityData" class="list-group" :key="group.id" ref="listGroup">
          <h2 class="list-group-title">{{ group.name }}</h2>
          <ul>
            <li v-for="item in group.cities" class="list-group-item line" :key="item.id"
                @click="selectCity(item.name)">
              <span class="name">{{ item.name }}</span>
            </li>
          </ul>
        </li>
      </ul>
      <div class="list-shortcut">
        <ul>
          <li v-for="(item, index) in shortcutList"
              class="item"
              :data-index="index"
              :key="item.id"
              @touchstart="onShortcutStart"
              @touchmove.stop.prevent="onShortcutMove"
              :class="{'current': currentIndex === index}">
            {{ item }}
          </li>
        </ul>
      </div>
    </div>

    <div class="search-content" ref="searchView" v-show="keyword">
      <ul>
        <li class="search-item" v-for="item in listItem" :key="item.id" @click="selectCity(item.name)"><span
          class="item-name">{{item.name}}</span>
        </li>
        <li v-show="hasNoData" class="empty">没有搜索到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
  import BScroll from 'better-scroll'
  import cityData from "../data/city-list"

  export default {
    data() {
      return {
        cityData: cityData,
        scrollY: 0,
        currentIndex: 0,
        keyword: "",
        showIcon: false,
        showIndex: true,
        cityList: [],
        cityName: "",
        list: cityData,
        listItem: [],
        hasNoData: false
      }
    },
    created() {
      this.touch = {};
      this.getHistory();
      //初始化better-scroll必须要等dom加载完毕
      setTimeout(() => {
        this._initScroll();
        this._calculateHeight();
      }, 20)
    },
    methods: {
      _initScroll() {
        this.scroll = new BScroll(this.$refs.listView, {
          probeType: 3,
          click: true
        });
        this.scroll.on('scroll', (pos) => {
          this.scrollY = pos.y;
        });
      },
      _initSearchScroll() {
        this.scroll = new BScroll(this.$refs.searchView, {
          probeType: 3,
          click: true
        });
      },
      onShortcutStart(e) {
        let index = e.target.getAttribute('data-index');//获取到绑定的index
        this.scrollToElement(index);//使用better-scroll的scrollToElement方法实现跳转
        let firstTouch = e.touches[0].pageY;//记录一下点击时候的Y坐标和index
        this.touch.y1 = firstTouch;
        this.touch.anchorIndex = index;
      },
      onShortcutMove(e) {
        let touchMove = e.touches[0].pageY;//再记录一下移动时候的Y坐标，然后计算出移动了几个索引
        this.touch.y2 = touchMove;//这里的16.7是索引元素的高度
        let delta = Math.floor((this.touch.y2 - this.touch.y1) / 16.7);
        //计算最后的位置
        let index = this.touch.anchorIndex * 1 + delta;//1是因为this.touch.anchorIndex是字符串，用 * 1偷懒的转化一下
        this.scrollToElement(index);
      },
      scrollToElement(index) {
        //处理边界情况,因为index通过滑动距离计算出来的,所以向上滑超过索引框框的时候就会<0，向上就会超过最大值
        if (index < 0) {
          return
        } else if (index > this.listHeight.length - 2) {
          index = this.listHeight.length - 2;
        }
        this.scrollY = -this.listHeight[index];//listHeight是正的，所以加个-
        this.scroll.scrollToElement(this.$refs.listGroup[index]);
      },
      _calculateHeight() {
        this.listHeight = [];
        const list = this.$refs.listGroup;
        let height = 0;
        this.listHeight.push(height);
        for (let i = 0; i < list.length; i++) {
          let item = list[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },
      selectCity(cityName) {//根据城市查询企业
        this.cityName = cityName;
        this.saveHistory();
        this.$emit("queryCompany", this.cityName);
      },
      backPage() {
        this.$router.go(-1);
      },
      saveHistory() {//存储最近访问数据
        let visit = localStorage.getItem("cityHistory");
        if (!visit) {
          visit = "";
        }
        if (visit.indexOf(this.cityName) > -1) {
          let list = visit.split(',');
          let data = [];
          list.forEach((value, index, array) => {
            if (value != this.cityName) {
              data.push(value);
            }
          });
          visit = data.join(",");
        }
        if (this.cityName != "china") {
          localStorage.setItem('cityHistory', visit == "" ? this.cityName : this.cityName + ',' + visit);
        }
        this.getHistory();
      },
      getHistory() {//获取最近访问数据
        let history = localStorage.getItem('cityHistory');
        if (history) {
          let array = history.split(',');
          if (array.length >= 2000) {
            localStorage.removeItem('cityHistory');
          } else if (array.length >= 2) {
            this.cityList = array.slice(0, 2);
          } else {
            this.cityList = array;
          }
        }
      }
    },
    watch: {
      scrollY(newVal) {
        //向下滑动的时候newVal是一个负数，所以当newVal>0时，currentIndex直接为0
        if (newVal > 0) {
          this.currentIndex = 0;
          return
        }
        //计算currentIndex的值
        for (let i = 0; i < this.listHeight.length - 1; i++) {
          let height1 = this.listHeight[i];
          let height2 = this.listHeight[i + 1];
          if (-newVal >= height1 && -newVal < height2) {
            this.currentIndex = i;
            return
          }
        }
        // 当超 -newVal > 最后一个高度的时候,因为 this.listHeight 有头尾，所以需要 - 2
        this.currentIndex = this.listHeight.length - 2
      },
      keyword() {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        if (!this.keyword) {//清空
          this.listItem = "";
          this.hasNoData = false;
          this.showIcon = false;
          this.showIndex = true;
          this.$nextTick(() => {
            this._initScroll();
            this._calculateHeight();
          });
          return;
        } else if (!(/^[\u2E80-\u9FFF]+$/).test(this.keyword)) {
          this.showIcon = true;
        }
        this.timer = setTimeout(() => {
          const result = []
          for (let i in this.list) {
            this.list[i].cities.forEach((value) => {//匹配搜索的条件
              if (value.name.indexOf(this.keyword) > -1) {
                result.push(value);
              }
            })
          }
          this.listItem = result;
          if (this.listItem.length <= 0) {
            this.hasNoData = true;//没有搜索的条件是否显示
          } else {
            this.hasNoData = false;
          }
        }, 100);
        this.showIndex = false;
        this.$nextTick(() => {
          this._initSearchScroll();
        });
      }
    },
    computed: {
      shortcutList() {
        return this.cityData.map((group) => {
          return group.name.substr(0, 1);
        })
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .box
    position: fixed
    width: 100%
    height: 100%
    background: #FFF
    .search-box
      display: flex
      align-items: center
      justify-content: flex-start
      width: 100%
      height: 1.373rem
      border-bottom: 1px solid rgba(230, 230, 230, 1)
      .back
        display: flex
        align-items: center
        padding-left: 0.533rem
        width: 0.267rem
        height: 0.493rem
      .search-con
        display: flex
        align-items: center
        margin: 0 auto
        width: 75%
        height: 0.75rem
        border-radius: 0.387rem
        background: #f7f7f7
        .logo
          padding-left: 0.2rem
          padding-right: 0.2rem
          width: 0.4rem
          height: 0.4rem
        .clear
          margin-left: auto
          width: 0.507rem
          height: 0.507rem
          padding-right: 0.2rem
        .search
          box-sizing: border-box
          height: 0.75rem
          line-height: 0.55rem
          background: #f7f7f7
          font-size: 0.427rem
          color: #999
    .recently-box
      margin-top: 0.25rem
      width: 100%
      height: auto
      background: #fff
      border-bottom: 1px solid #f7f7f7
      .title
        margin-bottom: 0.25rem
        padding-left: 0.533rem
        font-size: 0.373rem
        font-weight: bold
        color: rgba(102, 102, 102, 1)
      .recently-con
        display: flex
        padding-left: 0.533rem
        margin-bottom: 0.3rem
        color: #333
        .hot
          display: inline-block
          text-align: center
          margin-right: 0.267rem
          width: 2.4rem
          height: 0.75rem
          line-height: 0.75rem
          background: rgba(255, 255, 255, 1)
          border: 1px solid #e6e6e6
          border-radius: 0.093rem
          font-size: 0.373rem
          &:active
            background: #EEE
    .list-view
      position: fixed
      width: 100%
      top: 3.30rem
      bottom: 0
      overflow: hidden
      .list-group
        width: 100%
        height: auto
        .list-group-title
          display: flex
          align-items: center
          padding-left: 0.533rem
          height: 1.067rem
          font-size: 0.32rem
          color: #999
          background: #f7f7f7
        .list-group-item
          display: flex
          align-items: center
          height: 1.333rem
          &:active
            background: #EEE
        .line
          border-bottom: 1px solid #f7f7f7
          .name
            margin-left: 0.533rem
            color: #333333
            font-size: 0.373rem
      .list-shortcut
        position: absolute
        z-index: 30
        right: 0.35rem
        top: 46%
        transform: translateY(-50%)
        width: 0.533rem
        padding: 0.35rem 0
        border-radius: 0.267rem
        text-align: center
        background: rgba(167, 167, 167, 0.5)
        font-family: Helvetica
        .item
          padding: 0.08rem
          line-height: 1
          color: #666666
          font-size: 0.293rem
        .current
          color: #3cafff
    .search-content
      position: fixed
      width: 100%
      top: 3.30rem
      bottom: 0
      overflow: hidden
      .search-item
        display: flex
        align-items: center
        height: 1.333rem
        border-bottom: 1px solid #f7f7f7
        &:active
          background: #EEE
        .item-name
          margin-left: 0.533rem
          color: #333
          font-size: 0.373rem
      .empty
        display: flex
        justify-content: center
        margin-top: 2rem
        font-size: 0.453rem
        color: #666
</style>

